package com.oocl.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.exception.MyException;
import com.oocl.pojo.Purchaser;
import com.oocl.service.PurchaserService;
import com.oocl.service.impl.PurchaserServiceFactory;
import com.oocl.service.impl.ServiceFactory;



public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Logger logger = Logger.getLogger(LoginServlet.class);
		String name = request.getParameter("name");
		//System.out.println(name+"....");
		String pwd = request.getParameter("pwd");
		boolean isError = false;
		if(name==null||"".equals(name)){
			request.setAttribute("nameMsg", "name can not be emtry");
			isError = true;
		}
		if(pwd==null||"".equals(pwd)){
			request.setAttribute("pwdMsg", "password can not be emtry");
			isError = true;
		}
		
		if(isError){
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		
		Purchaser p = new Purchaser();
		p.setName(name);
		p.setPwd(pwd);
		
		try {
			PurchaserServiceFactory factory = (PurchaserServiceFactory) ServiceFactory
					.getServiceFactory(PurchaserServiceFactory.PURCHASER);
            
			PurchaserService  pSer = factory.getService();
			
			Purchaser purchaser = pSer.loadPerchaser(p);
			//System.out.println(purchaser.getName()+"purchase");
			if (purchaser!=null) {
				request.getSession().setAttribute("name", purchaser.getName());
				request.getSession().setAttribute("pId", purchaser.getId());
				request.getRequestDispatcher("items").forward(request, response);
				logger.info(name + "login......");
			} else {
				request.getRequestDispatcher("login.jsp").forward(request,
						response);
			}
		} catch (MyException e) {
			e.printStackTrace();
		}
	}

}
